package com.linkin.homepage.util;

import android.content.Context;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

import com.linkin.homepage.R;
import com.linkin.homepage.app.DemoApplication;


/**
 * Toast统一管理类
 */
public class ToastUitl {

    private static Toast sToast;

    /**
     * 短时间显示Toast
     *
     * @param message
     */
    public static void showShort(CharSequence message) {
        HandlerUtils.runOnUIThread(() -> showToast(message, Toast.LENGTH_SHORT));
    }


    /**
     * 短时间显示Toast
     *
     * @param strResId
     */
    public static void showShort(int strResId) {
        HandlerUtils.runOnUIThread(() -> showToast(DemoApplication.Companion.getApplication().getResources().getText(strResId), Toast.LENGTH_SHORT));
    }

    /**
     * 长时间显示Toast
     *
     * @param message
     */
    public static void showLong(CharSequence message) {
        showToast(message, Toast.LENGTH_LONG);
    }


    /**
     * 自定义显示Toast时间
     *
     * @param message
     * @param duration
     */
    public static void show(CharSequence message, int duration) {
        HandlerUtils.runOnUIThread(() -> showToast(message, duration));
    }

    /**
     * 自定义显示Toast时间
     *
     * @param context
     * @param strResId
     * @param duration
     */
    public static void show(Context context, int strResId, int duration) {
        HandlerUtils.runOnUIThread(() -> showToast(context.getResources().getText(strResId), duration));
    }

    private static void showToast(CharSequence message, int duration) {
        if (sToast != null) {
            sToast.cancel();
        }
        sToast = makeToast(DemoApplication.Companion.getApplication(), message, duration);
        sToast.setGravity(Gravity.CENTER, 0, 0);
        sToast.show();
    }

    private static Toast makeToast(Context context, CharSequence text, int duration) {
        Toast toast = new Toast(context);
        View v = LayoutInflater.from(context).inflate(R.layout.toast_text, null);
        TextView tv = v.findViewById(R.id.toast_message);
        tv.setText(text);
        toast.setView(v);
        toast.setDuration(duration);
        return toast;
    }
}
